package frontend.pages.admin.workplace;

import backend.service.admin.WorkplaceService;
import frontend.core.TimeTrackingWebApplication;
import frontend.model.admin.WorkplaceUIModel;
import frontend.pages.admin.base.AbstractManagingForm;
import frontend.components.base.ComponentFactory;
import org.apache.wicket.markup.html.panel.Panel;

public class WorkplaceForm extends AbstractManagingForm<WorkplaceUIModel> {

    private static final String RESOURCE_KEY_FIELD_LABEL_NAME = "pages.admin.workplace.form.name";
    private static final String RESOURCE_KEY_FIELD_LABEL_DESCRIPTION = "pages.admin.workplace.form.description";
    private static final String RESOURCE_KEY_FIELD_LABEL_IS_DEDUCTED = "pages.admin.workplace.form.isDeducted";
    private static final String RESOURCE_KEY_FIELD_LABEL_IS_ACTIVE = "pages.admin.workplace.form.isActive";

    private static final String VALIDATION_FORM_TEAM_SAME_WORKPLACE_NAME = "validation.form.workplace.sameWorkplaceName";

	public WorkplaceForm(String id, WorkplaceUIModel workplaceUIModel) {
		super(id, workplaceUIModel);		
	}

	@Override
	protected void constructFormContent() {
        Panel nameComponent = ComponentFactory.createTextFieldComponent("name", RESOURCE_KEY_FIELD_LABEL_NAME, uiModel);
        Panel descriptionComponent = ComponentFactory.createTextFieldComponent("description", RESOURCE_KEY_FIELD_LABEL_DESCRIPTION, uiModel);
        Panel isDeductedComponent = ComponentFactory.createCheckboxComponent("isDeducted", RESOURCE_KEY_FIELD_LABEL_IS_DEDUCTED, uiModel);
        Panel isActiveComponent = ComponentFactory.createCheckboxComponent("isActive", RESOURCE_KEY_FIELD_LABEL_IS_ACTIVE, uiModel);

		add(nameComponent, descriptionComponent, isDeductedComponent, isActiveComponent);
	}

    @Override
    protected Class getResponsePage() {
        return WorkplaceManagingPage.class;
    }

    @Override
    protected void doFormValidation() {
        validateNotEmpty(uiModel.getName(), RESOURCE_KEY_FIELD_LABEL_NAME);
        validateNotEmpty(uiModel.getDescription(), RESOURCE_KEY_FIELD_LABEL_DESCRIPTION);
        if ((uiModel.getName() != null) && nameWasChanged()) {
            WorkplaceService service =  TimeTrackingWebApplication.getService(WorkplaceService.class);
            if (service.findWorkplaceByName(uiModel.getName()) != null) {
                addFieldValidationError(RESOURCE_KEY_FIELD_LABEL_NAME, VALIDATION_FORM_TEAM_SAME_WORKPLACE_NAME);
            }
        }
    }

    private boolean nameWasChanged() {
        return (false == uiModel.getName().equals(uiModel.getDBModel().getName()));
    }
}
